package com.abu.crms.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.abu.crms.config.exception.CRException;
import com.abu.crms.pojo.Permission;
import com.abu.crms.pojo.RolePermission;
import com.abu.crms.mapper.RolePermissionMapper;
import com.abu.crms.service.PermissionService;
import com.abu.crms.service.RolePermissionService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 阿布
 * @since 2021-02-05
 */
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission> implements RolePermissionService {

    @Autowired
    private PermissionService permissionService;

    @Override
    @Transactional(rollbackFor = SQLException.class)
    public Boolean dynamicRemoveOrUpdatePermissions(String psIdStr, Long roleId) {
//        1.先删除当前角色下所以的权限信息
        this.remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
//        2.然后重新添加权限信息
        AtomicReference<Boolean> atomicReferenceFlag = new AtomicReference<>(false);
        if (StrUtil.isNotBlank(psIdStr)) {
            String[] psIdArray = StrUtil.split(psIdStr, ",");
//            遍历获取所有的id
            List<String> psIdList = Arrays.asList(psIdArray);
            psIdList.forEach(psId -> {
//                查询如果未保存才进行保存，父子都保存
//                全部选中（部分选中）
                RolePermission rpEntity = this.getOne(new QueryWrapper<RolePermission>().eq("role_id", roleId).eq("permission_id", psId));
                if (rpEntity == null) {
//                    保存用户权限列表以及它的父节点
                    RolePermission rolePermission = new RolePermission();
                    rolePermission.setRoleId(roleId);
                    rolePermission.setPermissionId(Convert.toLong(psId));
                    atomicReferenceFlag.set(this.save(rolePermission));
                }
            });
            return atomicReferenceFlag.get();
        }
        throw new CRException("更新成功，但没有给予任何菜单权限",204);
    }
}
